package cn.z2huo.datastructure.linearlist.doublelinkedlist;

import cn.z2huo.datastructure.linearlist.doublelinkedlist.entity.Node;

/**
 * 双向链表在指定位置插入一个结点
 * 作者：张一卓
 * 创建日期：2020/9/27
 */
public class ListInsert {
    public static void main(String[] args) {
        Node<Integer> root = DoubleLinkedListInit.integerInit();
        DoubleLinkedListUtils.printDoubleLinkedList(root);
        Node<Integer> element = new Node<>();
        element.setData(38);
        insert(root, 3, element);
        DoubleLinkedListUtils.printDoubleLinkedList(root);
    }

    public static <T> void insert(Node<T> root, int index, Node<T> element){
        Node<T> precursor = root;
        // h 0 1 2 3 4
        for (int i = 0; i < index; i++){
            precursor = precursor.getNext();
        }
        element.setPrior(precursor);
        element.setNext(precursor.getNext());
        precursor.setNext(element);
        element.getNext().setPrior(element);
    }
}
